import { excelBlobValidate } from '@/utils'
import request2 from '@/utils/request2'

import { saveAs } from 'file-saver'
// 登陆
export function Login(query) {
  return request2.post('/admin/login', query)
}

// 获取登录用户信息
export function GetCurrentUserInfo() {
  return request2.get('/admin/getInfo')
}

// 首页患者分布
export function getUserStage() {
  return request2({
    url: '/admin/homepage/userStage',
    method: 'get'
  })
}

// 首页教练列表
export function getCoach(query) {
  return request2('/admin/homepage/coach', query)
}

// 首页已预约教练的患者列表
export function GetReservedPatientsList(query) {
  return request2.get('/admin/homepage/userReserveList', { params: query })
}

// 患者列表
export function GetPatientsList(query) {
  return request2.get('/admin/user/userList', { params: query })
}

// 患者详情
export function GetUserDetail(userId) {
  return request2.get(`/admin/user/detail?userId=${userId}`)
}

export function DeleteUser(userId) {
  return request2.delete(`/admin/user/userInfo`, {
    params: { userId: userId }
  })
}

export function ChangeUserGroup(userId, userGroup) {
  const params = {
    userId: Number.parseInt(userId, 10),
    userGroup: Number.parseInt(userGroup, 10)
  }
  const encodedParams = Object.keys(params)
    .map(
      (key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
    )
    .join('&')

  console.log(encodedParams)

  return request2.put(`/admin/user/usergroup`, encodedParams, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

// 获取教练列表
export function GetCoachList(query) {
  return request2.post('/admin/coach/list', query)
}

// 获取教练详细信息
export function GetCoachDetail(query) {
  return request2.get(`/admin/coach/coachData?coachId=${query.coachId}`)
}

// 更新教练
export function UpdateCoach(query) {
  return request2.post('/admin/coach/update', query)
}

// // 监控消息列表
// export function PostUserMonitorList(query) {
//   return request2.post('/admin/userMonitor/list', query)
// }
// 监控消息列表
export function GetUserMonitorList(query) {
  return request2.get('/admin/userMonitor/list', { params: query })
}

// 首页患者列表
export function GetUserStage() {
  return request2.get('/admin/homepage/userStage')
}

export function GetHomepageCoach(date) {
  return request2.get(`/admin/homepage/coach?curDate=${date}`)
}

export function GetHomepageCoachName() {
  return request2.get(`/admin/homepage/coachNam`)
}

// 重置密码
export function resetUser(query) {
  return request2.put('/system/user/resetPwd', query)
}

// 新增用户
export function addUser(query) {
  return request2.post('/system/user', query)
}

// 监控消息处理
export function operateUserMonitor(id) {
  return request2.get(`/admin/userMonitor/operate?id=${id}`)
}

export function coachAdd(params) {
  return request2.post('/admin/coach/coachAdd', params)
}

export function GetAnxietyCycle(params) {
  return request2.get('/admin/user/getCourseAnxietyCycle', { params: params })
}

export function GetAnxietyLogList(query) {
  return request2.get(`/admin/user/anxietyLogList`, { params: query })
}

export function GetRelaxationList(query) {
  return request2.get(`/admin/user/relaxationList`, { params: query })
}

export function GetPriceList(query) {
  return request2.get(`/admin/user/priceList`, { params: query })
}

export function GetMoodRecordList(query) {
  return request2.get(`/admin/user/moodRecordList`, { params: query })
}

export function GetPraticeList(query) {
  return request2.get(`/admin/user/getPracStatic`, { params: query })
}

export function GetFollowList(query) {
  return request2.get(`/admin/userTrack/list`, { params: query })
}

export function AddFollowList(query) {
  return request2.post('/admin/userTrack/add', query)
}

export function GetSurveyDetailList(query) {
  return request2.get(`/admin/survey/detailList?${query}`)
}
export function PostSurveyDetailList(query) {
  // return request2.post(`/admin/survey/detailList`, query);
  return request2.post(`/admin/survey/detailList?${query}`)
}

export function GetSurveyList(query) {
  return request2.get('/admin/survey/list', { params: query })
}

export function GetSurveyAnswerList(query) {
  return request2.get('/admin/survey/detail', { params: query })
}

export function UploadFile(file, header) {
  const formData = new FormData()
  formData.append('file', file.file)

  return request2({
    method: 'post',
    headers: header,
    data: formData,
    url: '/admin/common/upload/',
    withCredentials: false,
    contentType: false
    // onUploadProgress: function(progressEvent) {
    //   console.log('progressEvent', progressEvent)
    // }
  })
}

export function UpdateGroupWeight(data) {
  return request2.post('/admin/homepage/updateWeight', data)
}
export function GetGroupInfo() {
  return request2.get('/admin/homepage/userGroupInfo')
}

export function GetH5List(query) {
  return request2.get(`/admin/h5Record/list?${query}`)
}
export function GetH5Detail(detailId) {
  return request2.get('/admin/h5Record/detail', { params: { id: detailId }})
}
export function GetH5Questions() {
  return request2.get('/h5/psycAsseQuestion/allList')
}
/**
 * 导出
 * */

export function ExportPatients(
  data,
  downloadFileName = '患者数据',
  downloadProgressCallback
) {
  return ExportExcel(
    '/admin/user/export',
    data,
    downloadFileName,
    downloadProgressCallback
  )
  // return request2.get('/admin/user/export', { params: data })
}

export function ExportMonitorMessages(data, downloadProgressCallback) {
  // return request2.get('/admin/userMonitor/export', { params: data })

  return ExportExcel(
    '/admin/userMonitor/export',
    data,
    '监控数据',
    downloadProgressCallback
  )
}

export function ExportQuestionnaires(data, downloadProgressCallback) {
  return ExportExcel(
    '/admin/survey/export',
    data,
    '问卷数据',
    downloadProgressCallback
  )
  // return request2.get('/admin/survey/export', { params: data })
}

export function ExportCoaches(data, downloadProgressCallback) {
  return ExportExcel(
    '/admin/coach/export',
    data,
    '教练数据',
    downloadProgressCallback
  )
  // return request2.get('/admin/coach/export', { params: data })
}

export function ExportExcel(
  url,
  params,
  downloadFileName,
  downloadProgressCallback
) {
  return request2({
    method: 'get',
    url: url,
    params: params,
    paramsSerializer: (params) => parseParams(params),
    responseType: 'blob',
    timeout: 500000,
    onDownloadProgress: (progressEvent) => {
      // console.log(progressEvent, progressEvent.loaded, progressEvent.currentTarget.response)
      // can't detect the total in current blob
      // const total = progressEvent.total // ? progressEvent.total : progressEvent.currentTarget.response.size
      // const loaded = progressEvent.loaded
      // const currentProgress = Math.round(
      //   (loaded * 100) / total
      // )
      downloadProgressCallback(progressEvent.loaded)
      // console.log('loaded: ', loaded)
    }
  }).then((res) => {
    const isBlob = excelBlobValidate(res.data)
    if (isBlob) {
      const blob = new Blob([res.data], { type: res.data.type })
      saveAs(blob, `${downloadFileName}.xls`)
    } else {
      console.error(res.data)
      // this.printErrMsg(res.data)
    }
  })
}

function parseParams(params) {
  const keys = Object.keys(params)
  let options = ''

  keys.forEach((key) => {
    const isParamTypeObject = typeof params[key] === 'object'
    const isParamTypeArray = isParamTypeObject && params[key].length >= 0

    if (!isParamTypeObject) {
      options += `${key}=${params[key]}&`
    }

    if (isParamTypeObject && isParamTypeArray) {
      params[key].forEach((element) => {
        options += `${key}=${element}&`
      })
    }
  })

  return options ? options.slice(0, -1) : options
}

// export function saveAs(text, name, opts) {
//   saveAs(text, name, opts)
// }
